from drf_yasg.utils import swagger_auto_schema
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_framework_simplejwt.authentication import JWTAuthentication

from apps.DepartManagement.models import Department
from apps.DepartManagement.serializers import DepartmentSerializer
from apps.utils.response_utils import api_response, ResponseCode


class GetDepartList(APIView):
    """
    获取部门列表
    """
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_description="获取部门列表",
        responses={200: '获取成功',
                   500: "系统内部错误"
                   },
        tags=['部门管理']
    )
    def get(self, request):
        try:
            # 查询所有部门
            departments = Department.objects.all()

            # 使用序列化器将部门对象转为 JSON 格式
            serializer = DepartmentSerializer(departments, many=True)
            return api_response(ResponseCode.SUCCESS, "获取成功", serializer.data)

        except Exception as e:
            # 捕获所有其他异常
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"服务器内部错误: {str(e)}")


class DepartCreateView(APIView):
    """
    批量创建部门
    """
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_description="批量创建部门",
        responses={200: '创建成功',
                   500: "系统内部错误"
                   },
        tags=['部门管理']
    )
    def post(self, request):
        try:
            # 定义部门列表
            depart_list = [
                "总经办", "财务部", "人事部", "行政部", "培训部", "信息部", "注册部", "AI视频部", "创新项目部",
                "商创项目部", "账号孵化部", "电商运营部", "数据分析部", "TIKTOK带货部", "新媒体运营部"
            ]

            # 创建空列表，用于存储部门对象
            departments = []

            # 使用 for 循环添加每个部门
            for name in depart_list:
                department = Department(name=name)
                departments.append(department)

            # 批量插入数据
            Department.objects.bulk_create(departments)

            return api_response(ResponseCode.SUCCESS, "创建成功")
        except ValidationError as e:
            return api_response(ResponseCode.BAD_REQUEST, f"请求参数错误: {str(e)}")
        except Exception as e:
            return api_response(ResponseCode.INTERNAL_SERVER_ERROR, f"服务器内部错误: {str(e)}")
